<?php
namespace app\admin\controller;
use think\Controller;
use think\Db;
use app\admin\model\Article as ArticleModel;
use think\File;

class Article extends Base {

    //列出文章
    public function lst(){
        $list = ArticleModel::select();

        if (empty($list)){
            $list = ArticleModel::paginate(3);
        }
        else{
            $list = ArticleModel::order("id desc")->paginate(3);
        }
        $this->assign("list",$list);
        return $this->fetch();
    }

    //添加文章
    public function add(){
        if (request()->isPost()){
            $data = [
                "title" => input("title"),
                "description" => input("description"),
                "content" => input("content"),
                "uptime" => time(),
            ];
            if($_FILES['image']['tmp_name']){
                $file = request()->file('image');
                $info = $file->move(ROOT_PATH . 'public' . DS . 'static/uploads');
                $data['image'] = 'static/uploads/'.$info->getSaveName();
                $data['image'] = str_replace("\\","/",$data['image']);
            }

            if (Db::name("article")->insert($data)){
                return $this->success("添加成功","lst");
            }
            else{
                return $this->error("添加失败");
            }
        }
        return $this->fetch();
    }

    //修改文章
    public function edit(){
        if (request()->isPost()) {
            $art = Db::table("article")->find(input("id"));
            $data = [
                "id" => input("id"),
                "title" => input("title"),
                "description" => input("description"),
                "content" => input("content"),
                "image" => $art['image']
            ];

            if($_FILES['image']['tmp_name']){
                if ($art['image']!=''){
                    unlink("public/".$art['image']);
                }

                $file = request()->file('image');
                $info = $file->move(ROOT_PATH . 'public' . DS . 'static/uploads');
                $data['image'] = 'static/uploads/'.$info->getSaveName();
                $data['image'] = str_replace("\\","/",$data['image']);
            }

            if (Db::table("article")->update($data)) {
                $this->success("修改文章成功", "lst");
            } else {
                $this->error("修改文章失败", "lst");
            }
        }
        $id = input('id');
        $article = Db::table("article")->find($id);
        $this->assign("article",$article);
        return $this->fetch();
    }

    //删除文章
    public function del(){
        $id = input('id');
        $article = Db::table("article")->find($id);
        if ($article['image']!=''){
            unlink("public/".$article['image']);
        }
        if (Db::table("article")->delete($id)){
            $this->success("删除文章成功","lst");
        }
        else{
            $this->error("删除文章失败","lst");
        }
    }
}